/*
 * @Author: chenjun 
 * @Date: 2021-12-13 14:21:27 
 * @Last Modified by:   jun.chen 
 * @Last Modified time: 2021-12-13 14:21:27 
 */
import React, { useState, useRef, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { Tabs, Button, message } from 'antd';
import { AppleOutlined, AndroidOutlined } from '@ant-design/icons';
import styles from './index.less';

import { TabType } from './data.d';

import { uuid } from '@/utils/utils';

import compDataTemp from './compDataTemp';
import FormAttributes from '@/components/drag/FormAttributes';
//comps
import DragComps from './sub-components/dragComps/dragComps';
import LayoutBox from './sub-components/layoutBox/layoutBox';
import PropertyConfig from './sub-components/propertyConfig/propertyConfig';
import PreviewModal from './sub-components/previewModal/previewModal';
// import ComponentConfig from '@/components/ComponentConfig';
import Loading from '@/pages/Drag/sub-components/previewModal/Loading';

import DragApi from './service';
import { useModel } from 'umi';

const { TabPane } = Tabs;

function DragLayout() {
  const [leftTabs] = useState<TabType[]>([
    {
      label: '页面',
      key: 'page',
      icon: <AppleOutlined />,
      content: '存放配置的页面',
    },
    {
      label: '组件',
      key: 'component',
      icon: <AndroidOutlined />,
      content: <DragComps onDragMenuStart={onDragMenuStart} />,
    },
    {
      label: '模板',
      key: 'template',
      icon: <AndroidOutlined />,
      content: '已配置好饿模板，可以直接使用在上面修改',
    },
  ]);
  const [showLoading, setLoding] = useState(false);
  const [layoutData, setLayoutData] = useState<any[]>([]);
  const [rigConTabKey, setRigConTabKey] = useState('attribute');

  const [compType, setCompType] = useState('');
  const [curCompIndex, setCurCompIndex] = useState<number>(0);
  const [dragCompStartIndex, setDragCompStartIndex] = useState<number | null>(null);
  const PropertyConfigRef = useRef<any>();
  const previewModalRef = useRef<any>();
  const history: any = useHistory();
  const Drag: any = useModel('drag');

  useEffect(() => {
    getFormInfo();
  }, [0]);

  async function getFormInfo() {
    const { id } = history.location.query;
    if (!id) return;
    // console.log(id);
    setLoding(true);
    const res = await DragApi.info(id);
    // console.log(res);
    const { infosData } = res.data;
    if (!infosData) return setLoding(false);
    const { layoutData: ldata, fieldShowRules, formEventObj } = JSON.parse(infosData);

    ldata.forEach((v: any) => {
      v.value = '';
      if (!v.id.startsWith(v.name)) {
        v.id = v.name + '-' + v.id;
      }
    });
    setLayoutData(ldata);
    Drag.fn.setFieldShowRule(fieldShowRules);
    Drag.fn.setFormEventObj(formEventObj);
    setLoding(false);
  }

  function onDragMenuStart(key: string) {
    // console.log(key)
    setCompType(key);
  }

  function onLayoutBoxDrop() {
    if (!compType) return console.warn('请勿拖拽非组件来布局');

    //获取相关组件数据模板
    const temp = compDataTemp()[compType];

    const data = [...layoutData];

    data.push(temp);
    // console.log(temp);
    setLayoutData(data);
    const index = data.length - 1;
    setCurCompIndex(index);
    PropertyConfigRef.current.setData(temp);
    setCompType('');
  }

  function delComp(id: string) {
    Drag.fn.removeShowRule(id);
    // console.log(id)
    const data = layoutData.filter((v) => v.id !== id);
    setLayoutData(data);
    setTimeout(() => {
      setCurCompIndex(data.length - 1);
      PropertyConfigRef.current.setData(data[data.length - 1]);
    }, 100);
  }
  function copyComp(item: any, index: number) {
    // console.log(item)
    const data = [...layoutData];
    const inx = index + 1;

    const copy = JSON.parse(JSON.stringify(item));
    copy.id = item.name + '-' + uuid();

    data.splice(inx, 0, copy);
    setLayoutData(data);

    setTimeout(() => {
      setCurCompIndex(inx);
      PropertyConfigRef.current.setData(data[inx]);
    }, 100);
  }

  function onCompClick(index: number) {
    setCurCompIndex(index);
    PropertyConfigRef.current.setData(layoutData[index]);
    PropertyConfigRef.current.setScrollTop();

    setRigConTabKey('attribute');
  }

  function onCompDragStart(index: number) {
    setDragCompStartIndex(index);
  }

  function onSpliceAddComp(index: number) {
    //获取相关组件数据模板
    const temp = compDataTemp()[compType];
    const data = [...layoutData];

    data.splice(index, 0, temp);
    // console.log(temp);
    setLayoutData(data);
    setCurCompIndex(index);
    PropertyConfigRef.current.setData(temp);
  }

  function subFormAddItem(item: any, index: number) {
    // console.log('subFormAddItem')
    // console.log(compType)
    const subs = ['input', 'select', 'datePicker', 'dateRange'];
    if (!subs.some((v) => v === compType)) return;
    const temp = compDataTemp()[compType];
    const data = [...layoutData];
    data[index].children[0].push(temp);
    // console.log(data[index].children);
    setLayoutData(data);
    PropertyConfigRef.current.setData(data[index]);
  }

  function onCompDrop(item: any, index: number, dragType: any) {
    if (item.name === 'subForm' && !dragType) {
      // console.log({item,index,dragType})
      return subFormAddItem(item, index);
    }

    if (!dragType) {
      return onSpliceAddComp(index);
    }

    let ldata = [...layoutData];
    if (!dragCompStartIndex && dragCompStartIndex !== 0) return;
    const startCompData = { ...ldata[dragCompStartIndex] };
    ldata = ldata.filter((v) => v.id !== startCompData.id);
    // startCompData.id = startCompData.name + '-' + uuid();
    // console.log({startCompData})
    ldata.splice(index, 0, startCompData);
    setLayoutData(ldata);

    setDragCompStartIndex(null);
    setCurCompIndex(index);
    PropertyConfigRef.current.setData(ldata[index]);
  }

  function onPropertyConfigChange(data: any) {
    // console.log(data);
    const ldata = [...layoutData];
    ldata[curCompIndex] = data;
    setLayoutData(ldata);
    PropertyConfigRef.current.setData(data);
  }

  function previewFunc() {
    previewModalRef.current.showModal();
  }

  function onSubFormDataChange(data: any, index: number) {
    // console.log(data);
    const ldata = [...layoutData];
    ldata[index].children = data;
    setLayoutData(ldata);
  }

  function onOpenValid() {
    Drag.fn.setContentItem(layoutData);
  }

  async function saveData() {
    setLoding(true);
    // console.log(history);
    const { id, name } = history.location.query;
    // if(!id || !name) return message.error('保存失败，请检查参数');
    // return
    const fieldShowRules = Drag.config.fieldShowRules || '';
    const formEventObj = Drag.config.formEventObj || '';
    const validators = Drag.config.validators || '';

    // return console.log(formEventObj)
    const infosData = {
      layoutData,
      fieldShowRules,
      formEventObj,
      validators,
    };

    const params = {
      id,
      name,
      infosData: JSON.stringify(infosData),
    };

    // return console.log(params);
    const res = await DragApi.save(params);

    message.success(res.errorMsg || '保存成功');
    // console.log(res);
    history.push('/home');
    setLoding(false);
  }

  console.log('layoutData', layoutData);

  return (
    <div className={styles.configCenter}>
      <div className={styles.lefcon}>
        <Tabs defaultActiveKey="component">
          {leftTabs.map((v) => (
            <TabPane
              tab={
                <span>
                  {v.icon}
                  {v.label}
                </span>
              }
              key={v.key}
            >
              {v.content}
            </TabPane>
          ))}
        </Tabs>
      </div>
      <div className={styles.dragCon}>
        <div className={styles.saveView}>
          <Button size="small" className={styles.view} onClick={previewFunc}>
            预览
          </Button>
          <Button size="small" type="primary" className={styles.save} onClick={saveData}>
            保存
          </Button>
        </div>
        <div className={styles.dragContent}>
          <LayoutBox
            layoutData={layoutData}
            onLayoutBoxDrop={onLayoutBoxDrop}
            copyComp={copyComp}
            delComp={delComp}
            onCompClick={onCompClick}
            onCompDrop={onCompDrop}
            onCompDragStart={onCompDragStart}
            curCompIndex={curCompIndex}
            onSubFormDataChange={onSubFormDataChange}
          />
        </div>
      </div>

      <div className={styles.rigCon}>
        <Tabs
          defaultActiveKey="attribute"
          activeKey={rigConTabKey}
          onTabClick={(key: string) => {
            setRigConTabKey(key);
          }}
        >
          <TabPane
            tab={
              <span>
                <AppleOutlined />
                属性配置
              </span>
            }
            key="attribute"
          >
            <PropertyConfig
              onOpenValid={onOpenValid}
              onPropertyConfigChange={onPropertyConfigChange}
              ref={PropertyConfigRef}
            />
          </TabPane>
          <TabPane
            tab={
              <span>
                <AndroidOutlined />
                表单配置
              </span>
            }
            key="logic"
          >
            <FormAttributes layoutData={layoutData} />
          </TabPane>
        </Tabs>
      </div>

      <PreviewModal
        ref={previewModalRef}
        formData={layoutData}
        formEvent={Drag.config.formEventObj}
      />
      {showLoading && <Loading />}
    </div>
  );
}

export default DragLayout;
